package biz.datalk.industrialland.admin.modules.externalapi.service.impl;

import biz.datalk.commons.utils.json.JsonUtil;
import biz.datalk.industrialland.admin.config.properties.SmsProperties;
import biz.datalk.industrialland.admin.modules.externalapi.model.vo.SmsResult;
import biz.datalk.industrialland.admin.modules.externalapi.service.ISmsService;
import biz.datalk.industrialland.common.util.AliyunUtil;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author tarofang@163.com
 * @date 2024-01-16
 */
@Slf4j
@Service
public class SmsServiceImpl implements ISmsService {

    private final SmsProperties smsProperties;

    public SmsServiceImpl(SmsProperties smsProperties) {
        this.smsProperties = smsProperties;
    }


    @Override
    public SmsResult sendCode(String mobile, String code) {
        if (StringUtils.isAnyBlank(mobile, code)) {
            return SmsResult.reqParamInvalid("参数错误");
        }

        SmsProperties.SmsType type = smsProperties.getType();
        switch (type) {
            case A_LI_YUN:
                return sendCodeByAliyun(mobile, code);
            // case TENCENT:
            //     break;
            default:
                return SmsResult.reqParamInvalid("未知的类型");
        }
    }

    private SmsResult sendCodeByAliyun(String mobile, String code) {
        try {
            Map<String, String> params = Maps.newHashMap();
            params.put("code", code);
            String templateParam = JsonUtil.getJsonFromObject(params);

            SmsProperties.Aliyun aliyunProp = smsProperties.getAliyun();
            SendSmsResponse sendSmsResponse = AliyunUtil.sendSms(aliyunProp.getAccessKeyId(), aliyunProp.getAccessSecret(), aliyunProp.getSignName(), mobile, aliyunProp.getTemplateCode(), templateParam, null);
            String jsonResult = JsonUtil.getJsonFromObject(sendSmsResponse, Boolean.TRUE);
            if (!"OK".equals(sendSmsResponse.getCode())) {
                log.error("sendCodeByAliyun fail:{}", jsonResult);
                return SmsResult.fail(SmsResult.CODE_FAIL_RESPONSE_RESULT, "发送失败", jsonResult);
            }

            return SmsResult.success(SmsResult.CODE_SUCCESS, "发送成功", jsonResult);
        } catch (Exception ex) {
            log.error("{}", ex.getMessage(), ex);
            return SmsResult.resResultInvalid("请求发生异常");
        }

    }
}
